package com.wfs.myapp.service.impl;

import com.wfs.myapp.common.ApiResult;
import com.wfs.myapp.entity.domain.User;
import com.wfs.myapp.entity.domain.bk.BkBook;
import com.wfs.myapp.entity.dto.req.user.LoginReqDTO;
import com.wfs.myapp.entity.dto.req.user.UserReqDto;
import com.wfs.myapp.entity.vo.BkBookVo;
import com.wfs.myapp.entity.vo.GroupListVo;
import com.wfs.myapp.entity.vo.UserVo;
import com.wfs.myapp.enums.BookStatusEnum;
import com.wfs.myapp.enums.ChannelTypeEnum;
import com.wfs.myapp.enums.ResponseCodeEnum;
import com.wfs.myapp.enums.SearchTypeEnum;
import com.wfs.myapp.remote.wx.WxRemoteService;
import com.wfs.myapp.remote.wx.vo.OpenIdVo;
import com.wfs.myapp.repository.UserRepository;
import com.wfs.myapp.repository.bk.BookRepository;
import com.wfs.myapp.repository.bk.GroupMemberRepository;
import com.wfs.myapp.repository.bk.GroupRepository;
import com.wfs.myapp.service.UserService;
import com.wfs.myapp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private GroupRepository groupRepository;

    @Autowired
    private GroupMemberRepository groupMemberRepository;

    @Autowired
    private WxRemoteService remoteService;

    @Value("${base.url}")
    private String baseUrl;

    @Override
    public ApiResult<List<User>> myGroupMemberList(Long userId) {
        // my groups
        List<Long> groupIds = groupMemberRepository.findGroupIdsByUserId(userId);
        // users in groups
        List<User> userList = userRepository.findByGroupIdIs(groupIds);
        userList = userList.stream().filter(user -> !user.getId().equals(userId)).collect(Collectors.toList());
        log.info("userlist: {}", userList);
        return ApiResult.success(userList);
    }

    @Override
    public ApiResult<UserVo> login(LoginReqDTO loginReqDTO) {
        UserVo userVo = new UserVo();
        if (ChannelTypeEnum.WEI_XIN.getCode().equals(loginReqDTO.getChannelType())) {
            OpenIdVo accessTokenVo = remoteService.getOpenId(loginReqDTO.getCode());
            User user = userRepository.findByOpenid(accessTokenVo.getOpenid());
            if (Objects.isNull(user)) {
                user = new User();
                user.setOpenid(accessTokenVo.getOpenid());
                user.setBirthday(LocalDate.of(2000, 01, 01));
                user.setCity("广东省 深圳市 南山区");
                user.setNickname("微信用户_"+accessTokenVo.getOpenid().substring(accessTokenVo.getOpenid().length() - 6));
                user.setAvatar(baseUrl + "/file/image" + SearchTypeEnum.TALK_RECORD.getPath() + "?imageName=" + "default-avatar.png");
                user.setStatus(1);
                user.setCreatedBy(user.getOpenid());
                user.setCreatedTime(LocalDateTime.now());
            }
            user.setUpdatedBy(user.getOpenid());
            user.setUpdatedTime(LocalDateTime.now());
            user.setLastLoginTime(LocalDateTime.now());
            user = userRepository.save(user);
            BeanUtils.copyProperties(user, userVo);
            userVo.setToken(JwtUtil.createToken(user));

        }
        // 将用户登录信息存储在本地缓存
//        CaffeineUtils.put(USER_CACHE_PRE + user.getId(), user);
        return ApiResult.success(userVo);
    }

    @Override
    public ApiResult<User> update(UserReqDto userReqDto) {
        Optional<User> byId = userRepository.findById(userReqDto.getId());
        if (!byId.isPresent()) return ApiResult.error(ResponseCodeEnum.USER_NOT_EXIST);
        User user = byId.get();
        BeanUtils.copyProperties(userReqDto, user);
        user.setUpdatedTime(LocalDateTime.now());
        user.setUpdatedBy(String.valueOf(userReqDto.getId()));
        userRepository.save(user);
        // 将用户登录信息存储在本地缓存
//        CaffeineUtils.put(USER_CACHE_PRE + user.getId(), user);
        return ApiResult.success(user);
    }

    @Override
    public ApiResult<UserVo> getUserInfo(Long userId) {
        UserVo userVo = new UserVo();
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) return ApiResult.error(ResponseCodeEnum.USER_NOT_EXIST);
        User user = userOpt.get();
        BeanUtils.copyProperties(user, userVo);
        // book list
        List<BkBook> bookList = bookRepository.findAllByUserId(userId);
        List<BkBookVo> bookVoList = new ArrayList<>();
        for (BkBook book : bookList) {
            BkBookVo bkBookVo = new BkBookVo();
            BeanUtils.copyProperties(book, bkBookVo);
            bkBookVo.setStatusStr(BookStatusEnum.getMsg(book.getStatus()));
            bookVoList.add(bkBookVo);
        }
        userVo.setBookList(bookVoList);
        // group list
        List<GroupListVo> groupList = groupRepository.findByUserId(userId);
        userVo.setGroupList(groupList);
        return ApiResult.success(userVo);
    }


}

